import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { login } from '/api/index'

const store = createStore({
  state: {
    token: '',
    userInfo: {},
    studentInfo: {}
  },
  getters: {},
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_INFO: (state, info) => {
      state.userInfo = info
    },
    SET_STUDENT_INFO: (state, info) => {
      state.studentInfo = info
    },
    CLEAR_STUDENT_INFO: (state, info) => {
      state.studentInfo = {}
    }
  },
  actions: {
    login({ commit }, params) {
      return new Promise((resolve, reject) => {
        login(params)
          .then((res) => {
            if (res.status === 200) {
              resolve(res)
              commit('SET_TOKEN', res.token)
              commit('SET_USER_INFO', res.data)
            } else {
              reject()
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    logout({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', {})
      uni.reLaunch({
        url: '/pages/login/index'
      })
    },
    goHome({ commit }) {
      commit('CLEAR_STUDENT_INFO')
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }
  },
  module: {},
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => uni.getStorageSync(key),
        setItem: (key, val) => uni.setStorageSync(key, val),
        removeItem: (key) => uni.removeStorageSync(key)
      }
    })
  ]
})

export default store
